package com.bobohost.crmrbac.web.controller;

import com.bobohost.crmrbac.service.EmployeeService;
import com.bobohost.crmrbac.util.ReturnObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

@Controller
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {
    private final EmployeeService employeeService;
//    @RequestMapping("/login")
//    @ResponseBody
//    public ReturnObject login(String username, String password) {
//        try {
//            employeeService.login(username,password);
//            return new ReturnObject();
//        } catch (Exception e) {
//
//            ReturnObject returnObject = new ReturnObject();
//            returnObject.mark("密码或用户名不正确");
//            return  returnObject;
//        }
//
//    }
//
//    @RequestMapping("/logout")
//    public String login(){
//        employeeService.logout();
//        return "redirect:/login.html";
//    }


    @RequestMapping("/login")
    @ResponseBody
    public ReturnObject login(String username, String password){


        //1.获取subject对象(用户)
        Subject subject = SecurityUtils.getSubject();


        //2.创建密码令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //3.登录
        try {
            subject.login(token);
            //登录成功
            log.debug("登录成功了，登录的用户名是：{}",username);
            return new ReturnObject();
        }catch (UnknownAccountException e){
            //用户名不正确
            e.printStackTrace();
            return new ReturnObject("用户名错误");
        }catch (IncorrectCredentialsException e){
            //用户名不正确
            e.printStackTrace();
            return new ReturnObject("密码错误");
        } catch (AuthenticationException e){
            e.printStackTrace();
            //4.处理结果
            //登录失败
            return new ReturnObject("登录失败，自己找原因，");
        }

    }


    /**
     * 退出注销
     * @return
     */
    @RequestMapping("/logout")
    public String login(){
//        employeeService.logout();
        SecurityUtils.getSubject().logout();
        return "redirect:/login.html";
    }

}
